package com.imoblife.brainwavestus;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.googleplay.billing.RestoreTransactions;
import com.imoblife.brainwavestus.customview.BasicDisplay;
import com.imoblife.brainwavestus.customview.PlayTimeWindows;
import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem;
import com.imoblife.brainwavestus.oldDownloadFrame.Commmand;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItemPragrame;
import com.imoblife.brainwavestus.oldMedia.LauncherMessage;
import com.imoblife.brainwavestus.oldMedia.MediaplayerFactory;
import com.imoblife.brainwavestus.oldMedia.SetVolumDialog;
import com.imoblife.brainwavestus.oldMedia.XlargerSetVolum;
import com.imoblife.brainwavestus.product.ProductInfo;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;
import com.imoblife.brainwavestus.user.User;
import com.imoblife.brainwavestus.util.AlertDialogUtil;
import com.imoblife.brainwavestus.util.DebugUtil;
import com.imoblife.brainwavestus.util.MakePurchaseStateChenge;
import com.imoblife.brainwavestus.util.ProductUtil;

import android.net.ConnectivityManager;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;

public class MainActivity extends BaseActivity {
	
	public static final String PLAY_TASK_NAME = "playTaskName";
	public static final String PLAY_TASK_CATEGORY = "playtaskcategory";
	public static final String PLAY_TASK_BRAINSTATE = "playtaskbrainstate";
	public static final String PLAY_TASK_TITLE = "playtasktitle";
	private static final String TAG = "MainActivity";
	public static int isStartMusic = 0; // 是否从曲库启动播放器。 1：要启动
	
	public PlayTimeWindows playTimeWindows;
	public BasicDisplay basicDisplay;
	public TextView taskNameTexView;
	public TextView categoryTextView;
	public TextView brainstateTextView;
	public String playTaskName;
	public CheckBox playcheck;
	public Button shopButton;
	public SeekBar musicSeekBar;
	public TextView left;
	public TextView right;
	public Store mStore;
	public User mUser;
	public long musicSize;
	public long currentPosition;
	public static int isOneCPU = 0; // 判断是否是单核CPU。

	public PowerManager.WakeLock mWakeLock;
	private RestoreTransactions restoreTask;
	public MediaplayerFactory mMediaplayerFactory;
	
	public enum PlayState {
		stop, start, pause,
	}

	public PlayState mPlayState = PlayState.stop;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (basicDisplay == null) {
			basicDisplay = new BasicDisplay(this);
		}
        
        if(LaunchScreenActivity.IS_PAD)
        {	
        	setContentView(R.layout.pad_main);
        }else {        	
        	setContentView(R.layout.phone_main);
        }
        
        init();
    }
  
	@Override
	protected void onStart() {	
		super.onStart();
		if (!isSdCardAvailableWrite()) {
			return;
		}
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		//playMusic();
	}

	@Override
	protected void onStop() {
		savePlayTaskName();
		super.onStop();
	}

	@Override
	protected void onResume() {
		
		super.onResume();
		
		//当主界面显示之后，可以认为整个应用程序已经初始化完成，下次再启动时，如果Application
		//还没有被系统消耗，可以直接使用初始化好的数据
		//若Application已经不存在，则重新初始化数据
		getBrainWavesApplication().setIsFirstLaunch(false);
		
		//if(isStartMusic == 1){
			playMusic();
		//}
	}

	@Override
	protected void onDestroy() {
		
		mPlayHandler.removeMessages(0);
		restoreTask.release();

		try {
			mMediaplayerFactory.clareListner();
			if (!mMediaplayerFactory.getBackgoundMediaPlayer().isPlaying()) {
				mMediaplayerFactory.destroyMediaPlayer();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		super.onDestroy();
		super.onDestroy();
	}

	private void init() {
		
		new Handler().postDelayed(new Runnable() {
			public void run() {
				if (DownLoadSchedulerSystem.getDownloadTaskState(
						Constant.FREE_WAVE_ID + Constant.MUSIC_FILE_SUFFIX,
						MainActivity.this) != DownLoadItemPragrame.DOWN_STATE_END) {
					Commmand.makeMusicDownloadCommand("calm_down.music",
							MainActivity.this);
				}
			}
		}, 10);
		
		mMediaplayerFactory = new MediaplayerFactory(this);
		if (!mMediaplayerFactory.isInitialized()) {
			mMediaplayerFactory.initializedMediaPlayer();
		}
		//initExceptionTracker();
		if (basicDisplay == null) {
			basicDisplay = new BasicDisplay(this);
		}
		
		mStore = getBrainWavesApplication().getStore();
		mUser = getBrainWavesApplication().getUser();
		
		initMusicTimeViews();
		initPlayerFrame();
		initPlayTaskName();
		updatePrograss();
		initVolumButton();
		playTimeWindows = new PlayTimeWindows(this);
		new LauncherMessage(this);
		OBpurchaseSystem.getOBpurchaseSystem(this).updateTapPoints();
		restoreTask = new RestoreTransactions(this);
		restoreTask.restoreTransactions();
	}
  
	public void onLibraryButtonClicked(View v){
		
		startActivity(new Intent(this,LibraryActivity.class));
	}
	
	public void onStoreButtonClicked(View v){
		
		startActivity(new Intent(this,StoreActivity.class));
	}
	
	public void onInfoButtonClicked(View v){
		
		startActivity(new Intent(this,InfoActivity.class));
	}
	
	/**
	 * 是否需要注册title_view的变化监听器
	 * 
	 * 因为main activity没有title view,所以，它不注册监听器
	 */
	@Override
	public boolean isNeedRegisterReceiver() {
		
		return false;
	}
	
	/**
	 * 不需要设置title的名称，因为main类没有这个控件
	 */
	@Override
	public boolean isNeedSetTitleName() {
		
		return false;
	}
	
	/**
	 * title view上menu点击的响应方法
	 * 
	 * 因为99%的类，都包含title view控件，所以把这个响应方法在父类里面设置为抽象类，要求所有子类都单独实现
	 * 这个方法
	 */
	@Override
	public void onTitleMenuClicked(View v) {
		
	}
	
	public String gettime(long durctions) {

		long mintue = durctions / 60000;

		long second = (durctions - mintue * 60000) / 1000;

		String mm = null, ss = null;

		if (mintue < 10) {
			mm = "0" + mintue;
		} else {
			mm = mintue + "";
		}

		if (second < 10) {
			ss = "0" + second;
		} else {
			ss = second + "";
		}
		System.out.println(mm + ":" + ss);

		return mm + ":" + ss;

	}
	
	public void initMusicTimeViews() {
		musicSeekBar = (SeekBar) findViewById(R.id.home_seekbar_music);
		musicSeekBar.setThumbOffset((int) (8 * getResources()
				.getDisplayMetrics().density + 0.5));
		left = (TextView) findViewById(R.id.left);
		right = (TextView) findViewById(R.id.right);

		musicSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onStopTrackingTouch(SeekBar seekBar) {
				if (playcheck.isChecked()) {

					try {
						mMediaplayerFactory.getBackgoundMediaPlayer().seek(
								currentPosition);
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {

				switch (mPlayState) {
				case start:
					if (fromUser) {
						currentPosition = progress;
					}

					if (currentPosition >= musicSize) {
						currentPosition = 0;
					}
					left.setText(gettime(currentPosition));
					right.setText("-" + gettime(musicSize - currentPosition));

					break;

				case pause:

					break;

				case stop:
					left.setText(gettime(currentPosition));
					right.setText("--:--");
					break;
				}
			}
		});

		try {
			if (mMediaplayerFactory.getBackgoundMediaPlayer().isPlaying()) {
				mPlayState = PlayState.start;
				currentPosition = mMediaplayerFactory.getBackgoundMediaPlayer()
						.position();
				musicSize = mMediaplayerFactory.getBackgoundMediaPlayer()
						.duration();

				musicSeekBar.setMax((int) musicSize);
				musicSeekBar.setProgress((int) currentPosition);

			}
		} catch (Exception e) {

		}

	}

	private void initPlayerFrame() {
		shopButton = (Button) findViewById(R.id.home_stop_button);
		playcheck = (CheckBox) findViewById(R.id.home_play_check);
		taskNameTexView = (TextView) findViewById(R.id.name);
		categoryTextView = (TextView) findViewById(R.id.category_text);
		brainstateTextView = (TextView) findViewById(R.id.brainstate_text);
		shopButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				try {
					stop();
				} catch (Exception e) {
				}
			}
		});

		if (mPlayState == PlayState.start) {
			playcheck.setChecked(true);
		}

		playcheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				try {
					if (isChecked) {
						if (Integer.parseInt(VERSION.SDK) < 8 || isOneCPU == 1) {
							if (checkDefaultAudioEnble()
									&& isConnectedNetwork()
									&& downloadTaskEnd()) {
								new AlertDialogUtil(MainActivity.this)
										.showAlertDialog(
												getResources()
														.getString(
																R.string.alertutil_title),
												getResources()
														.getString(
																R.string.alertutil_content_stopdownload),
												getResources()
														.getString(
																R.string.alertutil_dismiss));
								buttonView.setChecked(false);
								return;
							}
						}
						playUI();
					} else {
						pauseUI();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		});

	}

	void playUI() throws RemoteException {

		if (!checkDefaultAudioEnble()) {
			Toast.makeText(MainActivity.this, R.string.default_disable_message,
					Toast.LENGTH_LONG).show();
			Commmand.makeMusicDownloadCommand("calm_down.music",
					MainActivity.this);
			playcheck.setChecked(false);
			return;
		}

		if (mPlayState == PlayState.stop) {

			boolean isplaysucc = mMediaplayerFactory.getBackgoundMediaPlayer()
					.play(playTaskName + ".music");
			if (!isplaysucc) {
				makeFileError();
				return;
			}

		} else if (mPlayState == PlayState.pause) {
			mMediaplayerFactory.getBackgoundMediaPlayer().start();
		}
		playTimeWindows.startTimerRuning();
		mPlayState = PlayState.start;
		musicSeekBar.setEnabled(true);
		musicSize = mMediaplayerFactory.getBackgoundMediaPlayer().duration();
		musicSeekBar.setMax((int) musicSize);
		musicSeekBar.setProgress((int) currentPosition);
	}

	void pauseUI() throws RemoteException {

		if (mPlayState == PlayState.start) {
			mMediaplayerFactory.getBackgoundMediaPlayer().pause();
			mPlayState = PlayState.pause;
			musicSeekBar.setEnabled(false);
		} else if (mPlayState == PlayState.stop) {
			currentPosition = 0;

		}
	}

	Handler mPlayHandler;

	private void updatePrograss() {

		mPlayHandler = new Handler() {

			public void handleMessage(Message msg) {

				if (mPlayState == PlayState.start) {
					musicSeekBar.setProgress((int) currentPosition);
					currentPosition += 1000;
				}
				mPlayHandler.sendEmptyMessageDelayed(0, 1000);
			}

		};

		mPlayHandler.sendEmptyMessage(0);
	}

	void updataShopManagerSaveData() {
		SharedPreferences preferences = getSharedPreferences("ShopVersionCode",
				1);
		preferences.edit().putBoolean("isUpdate", true).commit();
	}

	private void initVolumButton() {
		if (basicDisplay.isXLargerScreen()) {

			new XlargerSetVolum(this);

		} else {
			new SetVolumDialog(this);
		}
	}

	private void initPlayTaskName() {
		SharedPreferences preferences = getSharedPreferences("musicName", 0);
		playTaskName = preferences.getString(PLAY_TASK_NAME, "calm_down");
		try {
			initMusicInfo(playTaskName);
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void savePlayTaskName() {
		SharedPreferences preferences = getSharedPreferences("musicName", 0);
		preferences.edit().putString(PLAY_TASK_NAME, playTaskName).commit();

	};

	private void initPlayMusicIcon(String playIntent) {
		DebugUtil.debug(TAG, "playTaskName>>" + playTaskName);

		if (playIntent.equals("Calm Down")) {
			playIntent = "calm_down";
		}

		ImageView icon = (ImageView) findViewById(R.id.frame_play_icon);	
		ProductInfo info = mStore.getProductByName(playIntent).getProductInfo();
		
		String iconPath = info.getParentId();
		
		try {
			icon.setImageBitmap(BitmapFactory.decodeStream(getAssets().open(
					"icon/" + iconPath + ".icon")));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	String playName = "";

	private void initMusicInfo(String playIntent)
			throws XmlPullParserException, IOException {

		DebugUtil.debug(TAG, "playIntent=" + playIntent);

		if (playIntent.equals("Calm Down")) {
			playIntent = "calm_down";
		}

		initPlayMusicIcon(playIntent);
		TextView textView = (TextView) findViewById(R.id.category_text);

		String state = "";
		String parent = mStore.getProductByName(playIntent).
						getProductInfo().getParentId();
		XmlPullParser parser = Xml.newPullParser();
		InputStream fileInputStream = null;
		fileInputStream = getAssets().open(
				"des/" + ProductUtil.getLang() + "/" + parent.replace(" ", "+")
						+ ".xml");
		parser.setInput(fileInputStream, "UTF-8");
		int evenType = 0;
		evenType = parser.getEventType();
		abc: while (evenType != XmlPullParser.END_DOCUMENT) {
			if (XmlPullParser.START_TAG == evenType) {

				for (int i = 0; i < parser.getAttributeCount(); i++) {
					if (parser.getAttributeName(i).equals("id")) {
						if (parser.getAttributeValue(i).equals(playIntent)) {
							break abc;
						}
					}
				}
			}
			evenType = parser.next();
		}

		for (int i = 0; i < parser.getAttributeCount(); i++) {

			if (parser.getAttributeName(i).equals("id")) {

			} else if (parser.getAttributeName(i).equals("name")) {
				playName = parser.getAttributeValue(i);
			} else if (parser.getAttributeName(i).equals("brainstate")) {
				state = parser.getAttributeValue(i);
			} else if (parser.getAttributeName(i).equals("category")) {
				textView.setText(parser.getAttributeValue(i));
			}

		}

		fileInputStream.close();
		taskNameTexView.setText(playName);
		brainstateTextView.setText(state);

		getSharedPreferences("playNametitle", -1).edit()
				.putString("playNametitle", playName).commit();

	}

	private String getPlayTaskIntent() {
		SharedPreferences preferences = (SharedPreferences) getSharedPreferences(
				"PlayTask", 0);
		String playTaskNameTmp;
		playTaskNameTmp = preferences.getString(PLAY_TASK_NAME, "");
		preferences.edit().remove(PLAY_TASK_NAME).commit();
		return playTaskNameTmp;
	}

	/**
	 * 检查默认音频是否下载完成
	 * 
	 * @return
	 */

	private boolean checkDefaultAudioEnble() {
		return !(playTaskName.equals("calm_down") && MakePurchaseStateChenge
				.getTaskState(playTaskName + ".music", this) != DownLoadItemPragrame.DOWN_STATE_END);

	}

	private void playMusic() {
		String playTaskIntent = getPlayTaskIntent();
		
		DebugUtil.debug(TAG, "play music name: " + playTaskIntent);
		if (playTaskIntent.equals("")) {
			return;
		}

		try {
			initMusicInfo(playTaskIntent);
		} catch (Exception e) {

		}

		if (playTaskIntent.equals(playTaskName)) {

			if (!playcheck.isChecked()) {
				playcheck.setChecked(true);
			}

		} else {
			playTaskName = playTaskIntent;
			if (playcheck.isChecked()) {
				playcheck.setChecked(false);
			}

			mPlayState = PlayState.stop;
			musicSeekBar.setProgress(0);
			musicSeekBar.setEnabled(false);
			currentPosition = 0;
			left.setText("00:00");
			right.setText("--:--");

			playcheck.setChecked(true);

		}

		DebugUtil.debug("MainActivity", "playTaskIntent=" + playTaskIntent);

	};

	private void stop() throws RemoteException {

		if (mPlayState == PlayState.start) {
			mMediaplayerFactory.getBackgoundMediaPlayer().stop();
			mPlayState = PlayState.stop;
			playcheck.setChecked(false);
			musicSeekBar.setProgress(0);
			musicSeekBar.setEnabled(false);
			currentPosition = 0;
			left.setText("00:00");
			right.setText("--:--");
		}

	}

	private void makeFileError() {
		Commmand.makeMusicReDownLoadCommand(playTaskName + ".music", this);
		playTaskName = "calm_down";
		savePlayTaskName();
		try {
			initMusicInfo(playTaskName);
		} catch (Exception e) {
		}
		playcheck.setChecked(false);
		mPlayState = PlayState.stop;

		new AlertDialog.Builder(this).setTitle(R.string.file_error)
				.setMessage(R.string.file_error_messeger)
				.setNegativeButton(R.string.ok, null).show();

	}

	public void finish() {
		savePlayTaskName();
		if (isConnectedNetwork() && downloadTaskEnd()) {
			displayExitDialog();
		} else {
			conformExit();
		}
	}

	long prevExit = -1;

	public void conformExit() {

		if (System.currentTimeMillis() - prevExit < 3000) {
			Commmand.makeExitDownLoadNowCommand(MainActivity.this);
			super.finish();			
			//super.clearStackActivity();
			//this.finish();
		} else {
			Toast.makeText(this, R.string.finish_massege, Toast.LENGTH_SHORT)
					.show();
			prevExit = System.currentTimeMillis();
		}

	}

	public boolean isConnectedNetwork() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		try {
			return cm.getActiveNetworkInfo().isConnected();
		} catch (Exception e) {
			return false;
		}
	}

	public boolean downloadTaskEnd() {
		SharedPreferences preferences = getSharedPreferences("downloadThread",
				0);
		return preferences.getBoolean("isDowning", false);

	}

	private void displayExitDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.exit_title)
				.setMessage(R.string.exit_messege)
				.setPositiveButton(R.string.exit_button_yes,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								Commmand.makeExitDownLoadNowCommand(MainActivity.this);
								// unbindService(mConnection);
								// exitSaveGoldToServer();
								MainActivity.super.finish();
							}
						})
				.setNegativeButton(R.string.exit_button_no,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								Commmand.makeExitDownLoadWaitCommand(MainActivity.this);
								// exitSaveGoldToServer();
								MainActivity.super.finish();
							}
						});
		builder.show();
	}

	public void defaultFinish() {
		Commmand.makeExitDownLoadWaitCommand(MainActivity.this);
		MainActivity.super.finish();
	}

	public boolean isSdCardAvailableWrite() {

		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	};

	private int getNumCores() {

		// Private Class to display only CPU devices in the directory listing

		class CpuFilter implements FileFilter {
			public boolean accept(File pathname) {
				// Check if filename is "cpu", followed by a single digit number
				if (Pattern.matches("cpu[0-9]", pathname.getName())) {
					return true;
				}
				return false;
			}
		}

		try {
			// Get directory containing CPU info
			File dir = new File("/sys/devices/system/cpu/");
			// Filter to only list the devices we care about
			File[] files = dir.listFiles(new CpuFilter());
			// Return the number of cores (virtual CPU devices)
			return files.length;
		} catch (Exception e) {
			// Default to return 1 core
			return 1;
		}
	}
}
